import hashlib
import hmac
import json
import requests.auth
import time
import sys

from coin.exchange.base.kr_rest.auth_base import AuthKey
from coin2.api_client.common import (SyncQueryer)


class CoincheckAuth(requests.auth.AuthBase):
  def __init__(self, key):
    self._key = AuthKey.from_file(key)
    self._access_token = self._key.access_key
    self._secret_key = self._key.secret_key

  def __call__(self, req: requests.PreparedRequest):
    nonce = str(round(time.time() * 1000000))
    url = req.url
    message = nonce + url
    signature = hmac.new(self._secret_key.encode(
        'utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest()
    req.headers.update({
        'ACCESS-NONCE': nonce,
        'ACCESS-KEY': self._access_token,
        'ACCESS-SIGNATURE': signature
    })

    return req


class CoincheckPrivateClient():
  def __init__(self, key, mea, ip=None):
    self._key = key
    if mea == "Spot.Coincheck.v1":
      self._url = 'https://coincheck.com'
    else:
      assert (0)
    self._auth = CoincheckAuth(key)
    self._query = SyncQueryer(api_host=self._url, auth=self._auth, ip=ip)

  def get_open_order(self, timeout=None):
    method = "GET"
    path = "/api/exchange/orders/opens"
    response = self._query.query(
        method=method, path=path, params=None, timeout=timeout)
    return response

  def get_account_balance(self, timeout=None):
    method = "GET"
    path = "/api/accounts/balance"
    response = self._query.query(
        method=method, path=path, params=None, timeout=timeout)
    return response

  def submit_order(self, timeout=None):
    method = "POST"
    path = "/api/exchange/orders"
    #params = {
    #    "pair": "btc_jpy",
    #    "order_type": "sell",
    #    "rate": "3000000",
    #    "amount": "0.005",
    #}
    params = {
        "pair": "btc_jpy",
        "order_type": "buy",
        "rate": "2900000",
        "amount": "0.005",
    }
    response = self._query.query(
        method=method, path=path, params=params, timeout=timeout)
    return response

  def cancel_order(self, order_id, timeout=None):
    method = "DELETE"
    path = "/api/exchange/orders/" + order_id
    response = self._query.query(
        method=method, path=path, params=None, timeout=timeout)
    return response


if __name__ == "__main__":
  key_path = sys.argv[1]
  config = {}
  mea = "Spot.Coincheck.v1"
  coincheck = CoincheckPrivateClient(key_path, mea)
  resp = coincheck.get_open_order()
  # resp = coincheck.get_account_balance()
  # resp = coincheck.submit_order()
  # resp = coincheck.cancel_order("5319411736")
  resp = resp.json()
  print(json.dumps(resp, indent=2))
